<template>
  <div class="app-container">
    <el-form v-model="form" label-position="right" label-width="150px">
      <el-form-item label="产品图片" required>
        <Upload
          typeName="prtPicture"
          :fileList="prtPictureList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
      <el-form-item label="产品名称" required>
        <el-input v-model.trim="form.prtName"></el-input>
      </el-form-item>
      <el-form-item label="产品货号" required>
        <el-input v-model.trim="form.prtCode"></el-input>
      </el-form-item>
      <el-form-item label="产品分类">
        <el-select v-model="form.prtType" placeholder="请选择活动区域">
          <el-option
            v-for="item of prtType"
            :key="item.uuid"
            :label="item.typeName"
            :value="item.typeName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品尺寸">
        <div class="size-box">
          <span>长</span>
          <el-input v-model.trim="form.prtLong" />
          <span>cm</span>
          <span>宽</span>
          <el-input v-model.trim="form.prtWide" />
          <span>cm</span>
          <span>高</span>
          <el-input v-model.trim="form.prtHigh" />
          <span>cm</span>
        </div>
      </el-form-item>
      <el-form-item label="产品规格">
        <el-input v-model.trim="form.prtSpecs"></el-input>
      </el-form-item>
      <el-form-item label="产品含量">
        <el-input v-model.trim="form.prtContent"></el-input>
      </el-form-item>
      <el-form-item label="产品发数">
        <el-input v-model.trim="form.prtHairNum"></el-input>
      </el-form-item>
      <el-form-item label="产品寸数">
        <el-input v-model.trim="form.prtInch"></el-input>
      </el-form-item>
      <el-form-item label="产品重量">
        <el-input v-model.trim="form.prtWeight"></el-input>
      </el-form-item>
      <el-form-item label="产品效果">
        <el-input v-model.trim="form.prtEffect"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model.trim="form.prtPrice"></el-input>
      </el-form-item>
      <el-form-item label="视频">
        <Upload
          typeName="prtVideo"
          :fileList="prtVideoList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
      <el-form-item label="产品详情">
        <Upload
          typeName="prtInfo"
          :fileList="prtDetailList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
      <el-form-item>
        <div class="switch-box">
          <span>上架：</span>
          <el-switch
            v-model.trim="form.isOn"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <span style="marginLeft:44px">镇店之宝：</span>
          <el-switch
            v-model.trim="form.zhenDian"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认提交</el-button>
      </el-form-item>
    </el-form>
    <Progress v-if="showProgress" :percentageNum="percentageNum" />
  </div>
</template>

<script>
import Upload from "@/components/upload";
import { getUploadKey, ossUpload } from "@/api/upload";
import { insertProduct, getProductTypeList } from "@/api";
export default {
  name: "AddProduct",
  components: {
    Upload
  },
  data() {
    return {
      //表单数据--------------------------------------------
      form: {
        prtName: "",
        prtCode: "",
        prtType: "",
        prtSpecs: "",
        prtContent: "",
        prtHairNum: "",
        prtInch: "",
        prtWeight: "",
        prtEffect: "",
        prtPrice: "",
        isOn: true,
        zhenDian: false,
        prtLong: "",
        prtWide: "",
        prtHigh: ""
      },
      //产品类型--------------------------------------------
      prtType: [],
      //产品图片列表--------------------------------------------
      prtPictureList: [],
      //产品视频列表--------------------------------------------
      prtVideoList: [],
      //产品详情列表--------------------------------------------
      prtDetailList: [],
      //上传文件数--------------------------------------------
      uploadFileNum: 0,
      //文件上传数--------------------------------------------
      uploadSuccessNum: 0,
      // 当前上传文件列表
      currentUploadList: [],
      //是否显示进度
      showProgress: false
    };
  },

  created() {
    this.getProductTypeList();
  },
  computed: {
    percentageNum() {
      let currentUpload = 0;
      let total = 0;
      this.currentUploadList.forEach(item => {
        currentUpload += item.loaded;
        total += item.total;
      });
      return ((currentUpload / total) * 100) | 0;
    }
  },
  methods: {
    //获取产品类型--------------------------------------------
    async getProductTypeList() {
      const shopUuid = this.$store.getters.shopUuid;
      const params = {
        page: 0,
        pageSize: 0,
        shopUuid
      };
      let res = await getProductTypeList(params).catch(err => console.log(err));
      if (!res) return;
      this.prtType = res.items;
    },

    //校验函数--------------------------------------------
    validatorFn(file) {
      return true;
    },

    // 表单校验
    validatorForm() {
      if (this.prtPictureList.length == 0) {
        this.$message({ type: "warning", message: "请添加产品图片" });
        return false;
      } else if (this.form.prtName == "") {
        this.$message({ type: "warning", message: "请添加产品名称" });
        return false;
      } else if (this.form.prtCode == "") {
        this.$message({ type: "warning", message: "请添加产品货号" });
        return false;
      }
      return true;
    },

    //确认提交--------------------------------------------
    async onSubmit() {
      //表单校验--------------------------------------------
      if (!this.validatorFn()) return;
      if (!this.validatorForm()) return;
      const shopUuid = this.$store.getters.shopUuid;
      //新增--------------------------------------------
      const data = {
        ...this.form,
        shopUuid
      };
      data.isOn = data.isOn ? 0 : 1;
      data.zhenDian = data.zhenDian ? 0 : 1;
      const res = await insertProduct(data);
      if (res.state == 100) {
        const fileList = this.prtPictureList
          .concat(this.prtVideoList)
          .concat(this.prtDetailList);
        this.uploadSuccessNum = 0;
        this.uploadFileNum = 0;
        this.showProgress = true;
        this.currentUploadList = [];
        fileList.forEach((fileItem, index) => {
          this.currentUploadList.push({
            loaded: 0,
            total: 0
          });
          this.uploadFileNum += 1;
          this.getUploadKey(res.items, fileItem, index);
        });
      }
    },

    //获取上传凭证--------------------------------------------
    async getUploadKey(shopData, fileItem, index) {
      const data = {
        fileName: fileItem.name,
        fileSize: fileItem.size,
        parentUuid: shopData.uuid,
        typeName: fileItem.typeName,
        shopUuid: shopData.shopUuid
      };
      const res = await getUploadKey(data);
      if (res.state == 100) {
        this.ossUpload(res.items, fileItem, index);
      }
    },

    //上传阿里云--------------------------------------------
    async ossUpload(key, fileItem, index) {
      const formData = new FormData();
      formData.append("policy", key.policy);
      formData.append("OSSAccessKeyId", key.accessid);
      formData.append("success_action_status", 200);
      formData.append("signature", key.signature);
      formData.append("key", key.dir);
      formData.append("file", fileItem.raw);
      const host = key.host;
      const res = await ossUpload(formData, host, this.uploadCallback, index);
      if (res.status === 200) {
        this.uploadSuccessNum += 1;
        if (this.uploadSuccessNum == this.uploadFileNum) {
          this.uploadSuccessNum = 0;
          this.uploadFileNum = 0;
          this.$message({ type: "success", message: "发布成功" });
          this.showProgress = false;
          this.$emit("updateData");
          this.dialogVisible = false;
        }
      }
    },

    //上传回调--------------------------------------------
    uploadCallback(progress, index) {
      let uploadData = {
        loaded: progress.loaded,
        total: progress.total
      };
      this.currentUploadList.splice(index, 1, uploadData);
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  max-width: 1080px;
}

::v-deep .el-form {
  .size-box {
    display: flex;

    & > span {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #646464;
      margin: 0 10px;
    }
  }

  .switch-box {
    & > span {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #646464;
    }
  }
}
</style>
